<template>
  <div>
    <div id="l-map"  style="width:400px;height:400px"></div>
    <div id="r-result">  请输入地址：
    <br/>
      <input type="text" id="txtKeyword" />
    <br/>
      <button @click="searchAddr">搜索</button>
    </div>
  </div>
</template>
<script>
export default {
  data(){
    return{

    }
  },
  created() {
    // 百度地图API功能
   const  map = new BMap.Map("l-map");            // 创建Map实例
    console.log(map)
    map.centerAndZoom("{$address}", 12);
    map.enableScrollWheelZoom();    //启用滚轮放大缩小，默认禁用
    map.enableContinuousZoom();    //启用地图惯性拖拽，默认禁用
    map.addControl(new BMap.NavigationControl());  //添加默认缩放平移控件
    map.addControl(new BMap.OverviewMapControl()); //添加默认缩略地图控件
    map.addControl(new BMap.OverviewMapControl({ isOpen: true, anchor: BMAP_ANCHOR_BOTTOM_RIGHT }));   //右下角，打开
 
    const local = new BMap.LocalSearch(map, {
        renderOptions: {map:map,autoViewport:true,selectFirstResult:false},
        pageCapacity:10
    });
 
    myIcon = new BMap.Icon("http://api.map.baidu.com/img/markers.png", new BMap.Size(23, 25), {
                    offset: new BMap.Size(10, 25),
                    imageOffset: new BMap.Size(0, 0 - 10 * 25)
                });
 
    
    var keys = new Array("{$address}");
 
    local.setSearchCompleteCallback(function (searchResults) {
            console.log(searchResults);
            if (typeof(searchResults) == "undefined" ) {
                alert("百度API没有搜索到该地址");
                return;
            }
            if(searchResults.length>0) {
                var searchResult = searchResults[0];
            }else {
                var searchResult = searchResults;
            }
            
            console.log(searchResult);
            
            var contents = [];
            for(var i=0; i<searchResult.getCurrentNumPois(); i++) 
            {
                //获得需要得到的坐标
                var poi = searchResult.getPoi(i);
                if (!poi) {
                    alert("百度API没有搜索到该地址");
                }
                // console.log(poi);
        
                //设置中心点
                map.centerAndZoom(poi.point, 13);
                // 创建标注，为要查询的地方对应的经纬度
                var marker = new BMap.Marker(new BMap.Point(poi.point.lng, poi.point.lat),{ icon: myIcon });
                //alert("["+poi.point.lng+","+poi.point.lat+"]");
                //在地图上添加标识
                map.addOverlay(marker);
                //点击标识后显示的内容
                contents[i] = "你要查找的地方:【"+poi.title+"】<br/>地址："+poi.address+"<br/>经度："+poi.point.lng+"<br/>纬度："+poi.point.lat;
                
                marker.setTitle(contents[i]);
              
                    
            }
            
        });
    local.search(keys);
  },
  methods :{
    searchAddr() {
      var keys = document.getElementById("txtKeyword").value;
        local.search(keys);
    }
  }

}

 
</script>
<style>

</style>
